import FriendsStateStore from "@/store/friend";
import { getFriendList, updateFriendRemark } from "@/services/api/friend";
import { ResponseCode } from "@/types/api-common";
import AlertService from "@/components/Global/Alert/service";
import { DEFAULT_AVATAR_URL } from "@/config/default-value";
import { countFriendRequestsApi } from "@/services/api/friend-request";
import { getUserProfileByID } from "@/services/api/user";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {Friend, FriendStatus} from "@/types/friend";
import {getISODateTime} from "@/utils/time-utils";

export const useFriendsState = () => FriendsStateStore((state) => state.state);

export const useFriendsActions = () => {
  const {
    setFriends,
    setLoading,
    setError,
    setFriendInfo,
    setTotalUnreadFriendRequests,
    updateFriendRemark: storeUpdateFriendRemark,
  } = FriendsStateStore((state) => state.actions);
  const {currentUser} = useUserProfileState()

  async function fetchFriends() {
    try {
      setError(null);
      setLoading(true);
      const resp = await getFriendList();
      if (resp.data.code === ResponseCode.SUCCESS) {
        const self: Friend = {
          id: currentUser.id,
          createTime: getISODateTime(new Date(currentUser.createTime * 1000)),
          remark: "我",
          uuid: currentUser.uuid,
          nickname: currentUser.nickname,
          avatar: currentUser.avatar || DEFAULT_AVATAR_URL,
          friendStatus: FriendStatus.ONLINE,
          lastOnlineTime: null
        };
        const friends = resp.data.data.map((f) => ({
          ...f,
          avatar: f.avatar || DEFAULT_AVATAR_URL,
        }));
        friends.unshift(self); // 将自己添加到好友列表的开头
        friends.sort((a, b) => a.createTime.localeCompare(b.createTime));
        setFriends(friends);
        setLoading(false);
        return friends;
      } else {
        setLoading(false);
        return [];
      }
    } catch (error) {
      console.error("获取好友列表失败:", error);
      setError(error);
      AlertService.showAlert("error", "获取好友失败");
      setLoading(false);
      return [];
    }
  }

  async function fetchFriendRequestsCount() {
    let unreadCount = 0;
    try {
      const resp = await countFriendRequestsApi();
      if (resp.data.code === ResponseCode.SUCCESS) {
        unreadCount = resp.data.data;
      } else {
        console.error(
          "Error fetching friend requests count:",
          resp.data.message
        );
        unreadCount = 0;
      }
    } catch (error) {
      console.error("Error fetching friend requests count:", error);
      unreadCount = 0;
    } finally {
      setTotalUnreadFriendRequests(unreadCount);
    }
  }

  async function fetchFriendInfo(id: string) {
    const resp = await getUserProfileByID(id);
    if (resp.data.code === ResponseCode.SUCCESS) {
      const friend = resp.data.data;
      // 确保头像有默认值
      friend.avatar = friend.avatar || DEFAULT_AVATAR_URL;
      // 设置当前好友的UUID
      setFriendInfo(friend);
    }
  }
  /**
   * 更新好友备注
   * @param friendId 好友的ID
   * @param remark 新的备注名
   * @returns 是否更新成功
   */
  async function updateFriendRemarkByUuid(
    friendId: string,
    remark: string
  ): Promise<boolean> {
    try {
      const resp = await updateFriendRemark({ friendId, remark });
      if (resp.data.code === ResponseCode.SUCCESS) {
        // 更新本地存储
        await storeUpdateFriendRemark(friendId, remark);
        AlertService.showAlert("success", "备注修改成功");
        return true;
      } else {
        console.error("更新好友备注失败:", resp.data.message);
        AlertService.showAlert("error", "备注修改失败");
        return false;
      }
    } catch (error) {
      console.error("更新好友备注异常:", error);
      AlertService.showAlert("error", "备注修改失败");
      return false;
    }
  }
  /**
   * 获取当前好友的信息（包括ID和备注等）
   * @returns 当前好友的完整信息，如果找不到则返回null
   */
  function getCurrentFriendFullInfo() {
    const { currentFriend, friends } = FriendsStateStore.getState().state;
    if (!currentFriend) return null;

    // 从好友列表中查找匹配的好友信息
    const friendInfo = friends.find((f) => f.uuid === currentFriend.uuid);
    return friendInfo || null;
  }

  return {
    fetchFriends,
    fetchFriendRequestsCount,
    fetchFriendInfo,
    updateFriendRemarkByUuid,
    getCurrentFriendFullInfo,
  };
};
